package cn.xin.org.service.impl;

import cn.xin.base.enums.ShopStateEnum;
import cn.xin.base.query.BaseQuery;
import cn.xin.base.service.impl.BaseServiceImpl;
import cn.xin.base.util.*;
import cn.xin.base.vo.EchartsMiddleVo;
import cn.xin.base.vo.EchartsVo;
import cn.xin.org.domain.Employee;
import cn.xin.org.domain.Shop;
import cn.xin.org.domain.ShopAuditLog;
import cn.xin.org.dto.ShopAuditDto;
import cn.xin.org.dto.ShopDto;
import cn.xin.org.mapper.EmployeeMapper;
import cn.xin.org.mapper.ShopAuditLogMapper;
import cn.xin.org.mapper.ShopMapper;
import cn.xin.org.service.IShopService;
import cn.xin.user.domain.Logininfo;
import cn.xin.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.validation.Valid;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xin
 * @since 2022-12-26
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private LogininfoMapper logininfoMapper;


    @Override
    public void settlement(Shop shop) {
        //检验参数 注解

        //百度AI审核
        Boolean textCensor = BaiduAuditUtils.TextCensor(shop.getName());
        if (!textCensor){
            throw new BussinessException("店铺名违规");
        }
        Boolean imgCensor = BaiduAuditUtils.ImgCensor(shop.getLogo());
        if (!imgCensor){
            throw new BussinessException("店铺logo违规");
        }

        //两次密码是否相同
        if(!shop.getAdmin().getPassword().equals(shop.getAdmin().getComfirmPassword())){
            throw new BussinessException("密码不相同");
        }


        //店铺是否重复(店铺名)
        String shopName = shop.getName();
        Shop shop1 = shopMapper.finByName(shopName);
        if (shop1 != null){
            throw new BussinessException("已有此店铺,请登录");
        }

        //管理员是否已有店铺
        String empUserName = shop.getAdmin().getUsername();//获取用户名

        Employee employee = employeeMapper.findByName(empUserName);//查询数据库是否有该店铺信息
        if (employee != null && employee.getShopId() != null){//判断是否有此用户且店铺是否
            // 不为空只能判断当前人属于这个店铺，但他不一定是管理员
            shop1 = shopMapper.findByAdminId(employee.getId());
            if (shop1 != null){
                throw new BussinessException("当前人是管理员，已有店铺");
            }
        }


        //添加数据
        shop.setRegisterTime(new Date());
        shop.setState(0);
        super.add(shop);
        // emp
        Employee admin = shop.getAdmin();
        //获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        admin.setSalt(salt);
        //获取加密密码
        String password = MD5Utils.encrypByMd5(salt + admin.getPassword());
        admin.setPassword(password);

        admin.setAge(18);
        admin.setState(1);
        admin.setShopId(shop.getId());
        Logininfo logininfo = new Logininfo();
        logininfo.setType(0);
        logininfo.setDisable(1);

        BeanUtils.copyProperties(admin,logininfo);
        logininfoMapper.add(logininfo);
        admin.setLogininfoId(logininfo.getId());
        employeeMapper.add(admin);

        //修改shop字段
        Shop updateShop = new Shop();
        updateShop.setId(shop.getId());
        updateShop.setAdminId(admin.getId());
        super.update(updateShop);
    }

    @Override
    public void auditPass(ShopAuditDto shopAuditDto) {
        //参数校验 注解

        //修改状态 店铺状态：0待审核，1.审核通过/待激活，2.审核驳回 3.已激活
        Shop shop = new Shop();
        shop.setId(shopAuditDto.getShopId());
        shop.setState(1);
        shopMapper.update(shop);
        //保存日志
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        shopAuditLog.setNote(shopAuditDto.getNote());
        shopAuditLog.setShopId(shopAuditDto.getShopId());
        shopAuditLog.setAuditTime(new Date());
        shopAuditLog.setAuditId(1L);
        shopAuditLogMapper.add(shopAuditLog);
        //发送邮件通知用户去激活
        try {
            // 1.创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            // 2.发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("1621439152@qq.com");
            helper.setSubject("测试复杂邮件");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>点击此链接激活你的店铺</h1>" +
                    "http://localhost:8080/shop/activation/" + shopAuditLog.getShopId(),true);
            // 4.添加附件
            //helper.addAttachment("好东西.jpg",new File("E:\\JAVA\\imgs\\图2.jpg"));
            // 5.设置收件人
            helper.setTo("1621439152@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

    }
    //驳回
    @Override
    public void auditReject(ShopAuditDto shopAuditDto) {
        Shop shop = new Shop();
        shop.setId(shopAuditDto.getShopId());
        shop.setState(2);
        shopMapper.update(shop);

        //保存日志
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        shopAuditLog.setNote(shopAuditDto.getNote());
        shopAuditLog.setShopId(shopAuditDto.getShopId());
        shopAuditLog.setAuditTime(new Date());
        shopAuditLog.setAuditId(1L);
        shopAuditLogMapper.add(shopAuditLog);

        //发送邮件通知用户去激活
        try {
            // 1.创建复杂邮件对象
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            // 2.发送复杂邮件的工具类
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom("1621439152@qq.com");
            helper.setSubject("测试复杂邮件");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>点击此链接激活你的店铺</h1>" +
                    "http://localhost:8081/#/registerAgain?shopId=" + shopAuditLog.getShopId(),true);
            // 4.添加附件
            //helper.addAttachment("好东西.jpg",new File("E:\\JAVA\\imgs\\图2.jpg"));
            // 5.设置收件人
            helper.setTo("1621439152@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

    }

    //修改
    @Override
    public void settlementAgain(ShopDto shopDto) {

        Shop shop = shopDto.getShop();

        shopMapper.update(shop);

    }

//    //导入
//    @Override
//    public void importExcel(List<Shop> shops) {
//        shopMapper.importExcel(shops);
//    }

    //激活
    @Override
    public void activation(Long id) {
        Shop shop = new Shop();
        shop.setState(3);
        shop.setId(id);
        shopMapper.update(shop);

    }

    //报表
    @Override
    public EchartsVo echarts() {
        List<EchartsMiddleVo> middleVosList = shopMapper.echarts();
        EchartsVo echartsVo = new EchartsVo();

        List<String> x = middleVosList.stream().map(middle -> ShopStateEnum.getNameByCode(middle.getX())).collect(Collectors.toList());
        echartsVo.setX(x);
        List<Integer> y = middleVosList.stream().map(EchartsMiddleVo::getY).collect(Collectors.toList());
        echartsVo.setY(y);

        return echartsVo;
    }


    @Override
    public PageList<Shop> queryByPage(BaseQuery query) {
        //获取店铺列表
        PageList<Shop> shopPageList = super.queryByPage(query);
        //判断是否为空
        if(shopPageList == null || CollectionUtils.isEmpty(shopPageList.getRows())){
            return new PageList<>(0,new ArrayList<>());
        }
        //获取列表每行的集合 店铺
        List<Shop> shopPageListRows = shopPageList.getRows();
        //获取每行的id集合 店铺
        List<Long> ids = shopPageListRows.stream().map(Shop::getId).collect(Collectors.toList());

        //根据id查询出所有日志
        List<ShopAuditLog> logs = shopAuditLogMapper.findByShopIds(ids);
        //根据shopId对日志进行分组
        Map<Long, List<ShopAuditLog>> logListMap = logs.stream().collect(Collectors.groupingBy(ShopAuditLog::getShopId));

        //遍历每行的集合
        shopPageListRows.forEach(shop -> {
            //通过日志的shopId和店铺的id获取对应的日志集合
            List<ShopAuditLog> logList = logListMap.get(shop.getId());
            // 判断该店铺的日志集合是否为空
            if (CollectionUtils.isEmpty(logList)) {
                logList = new ArrayList<>();
            }
            //把日志的集合放入对应的店铺中
            shop.setAuditLogs(logList);
        });
        return shopPageList;
    }
}
